package com.tanhua.dubbo.api.impl;
import org.bson.types.ObjectId;

import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Friend;
import com.tanhua.domain.mongo.UserLike;
import com.tanhua.domain.mongo.Visitors;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.domain.vo.UserLikeVo;
import com.tanhua.dubbo.api.RecommendUserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.UserLikeApi;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserLikeApiImpl implements UserLikeApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private UserInfoApi userInfoApi;

    @Autowired
    private RecommendUserApi recommendUserApi;


    @Override
    // 互相关注数，db.tanhua_users.count({userId:1})
    public Long queryEachLoveCount(Long userId) {
        Query query = new Query(Criteria.where("userId").is(userId));
        long count = mongoTemplate.count(query, Friend.class);
        return count;
    }

    @Override
    // 喜欢数，db.user_like.count({userId:1})
    public Long queryLoveCount(Long userId) {
        Query query = new Query(Criteria.where("userId").is(userId));
        long count = mongoTemplate.count(query, UserLike.class);
        return count;
    }

    @Override
    // 粉丝数，db.user_like.count({likeUserId:1})
    public Long queryFansCount(Long userId) {
        Query query = new Query(Criteria.where("likeUserId").is(userId));
        long count = mongoTemplate.count(query, UserLike.class);
        return count;
    }

    @Override
    public PageResult queryEachLoveList(Long userId, Integer page, Integer pagesize) {
        // 创建查询对象
        Query query = new Query(Criteria.where("userId").is(userId));
        // 指定排序参数
        query.with(Sort.by(Sort.Order.desc("created")));
        // 指定分页参数
        query.limit(pagesize).skip((page - 1) * pagesize);

        // 查询当前页数据
        List<Friend> friendList = mongoTemplate.find(query, Friend.class);
        // 查询总条数
        long count = mongoTemplate.count(query, Friend.class);

        // 封装返回结果
        List<UserLikeVo> voList = new ArrayList<>();

        if (friendList != null && friendList.size() > 0) {
            for (Friend friend : friendList) {
                // 创建vo
                UserLikeVo vo = new UserLikeVo();

                // 封装vo
                vo.setId(friend.getFriendId());
                // 查询好友详情
                UserInfo userInfo = userInfoApi.findById(friend.getFriendId());
                if (userInfo != null) {
                    BeanUtils.copyProperties(userInfo, vo);
                }

                // 查询你和好友的缘分值
                long score = recommendUserApi.queryScore(userId, friend.getFriendId());
                vo.setMatchRate((int) score);

                // 添加vo到集合
                voList.add(vo);
            }
        }

        return new PageResult(page, pagesize, (int) count, voList);
    }

    @Override
    // db.user_like.find({userId:1})
    public PageResult queryLoveList(Long userId, Integer page, Integer pagesize) {
        // 创建查询对象
        Query query = new Query(Criteria.where("userId").is(userId));
        // 指定排序参数
        query.with(Sort.by(Sort.Order.desc("created")));
        // 指定分页参数
        query.limit(pagesize).skip((page - 1) * pagesize);

        // 查询当前页数据
        List<UserLike> userLikeList = mongoTemplate.find(query, UserLike.class);
        // 查询总条数
        long count = mongoTemplate.count(query, UserLike.class);

        // 封装返回结果
        List<UserLikeVo> voList = new ArrayList<>();

        if (userLikeList != null && userLikeList.size() > 0) {
            for (UserLike userLike : userLikeList) {
                // 创建vo
                UserLikeVo vo = new UserLikeVo();

                // 封装vo
                vo.setId(userLike.getLikeUserId());
                // 查询喜欢的人详情
                UserInfo userInfo = userInfoApi.findById(userLike.getLikeUserId());
                if (userInfo != null) {
                    BeanUtils.copyProperties(userInfo, vo);
                }

                // 查询你和喜欢的人的缘分值
                long score = recommendUserApi.queryScore(userId, userLike.getLikeUserId());
                vo.setMatchRate((int) score);

                // 添加vo到集合
                voList.add(vo);
            }
        }

        return new PageResult(page, pagesize, (int) count, voList);
    }

    @Override
    // db.user_like.find({likeUserId:1})
    public PageResult queryFansList(Long userId, Integer page, Integer pagesize) {
        // 创建查询对象
        Query query = new Query(Criteria.where("likeUserId").is(userId));
        // 指定排序参数
        query.with(Sort.by(Sort.Order.desc("created")));
        // 指定分页参数
        query.limit(pagesize).skip((page - 1) * pagesize);

        // 查询当前页数据
        List<UserLike> userLikeList = mongoTemplate.find(query, UserLike.class);
        // 查询总条数
        long count = mongoTemplate.count(query, UserLike.class);

        // 封装返回结果
        List<UserLikeVo> voList = new ArrayList<>();

        if (userLikeList != null && userLikeList.size() > 0) {
            for (UserLike userLike : userLikeList) {
                // 创建vo
                UserLikeVo vo = new UserLikeVo();

                // 封装vo
                vo.setId(userLike.getUserId());
                // 查询粉丝的详情
                UserInfo userInfo = userInfoApi.findById(userLike.getUserId());
                if (userInfo != null) {
                    BeanUtils.copyProperties(userInfo, vo);
                }

                // 查询你和粉丝的缘分值
                long score = recommendUserApi.queryScore(userId, userLike.getUserId());
                vo.setMatchRate((int) score);

                // 添加vo到集合
                voList.add(vo);
            }
        }

        return new PageResult(page, pagesize, (int) count, voList);
    }

    @Override
    // 谁看过我，db.visitors.find({userId:1})
    public PageResult queryVisitorsList(Long userId, Integer page, Integer pagesize) {
        // 创建查询对象
        Query query = new Query(Criteria.where("userId").is(userId));
        // 指定排序参数
        query.with(Sort.by(Sort.Order.desc("date")));
        // 指定分页参数
        query.limit(pagesize).skip((page - 1) * pagesize);

        // 查询当前页数据
        List<Visitors> visitorsList = mongoTemplate.find(query, Visitors.class);
        // 查询总条数
        long count = mongoTemplate.count(query, Visitors.class);

        // 封装返回结果
        List<UserLikeVo> voList = new ArrayList<>();

        if (visitorsList != null && visitorsList.size() > 0) {
            for (Visitors visitors : visitorsList) {
                // 创建vo
                UserLikeVo vo = new UserLikeVo();

                // 封装vo
                vo.setId(visitors.getVisitorUserId());
                // 查询访客的详情
                UserInfo userInfo = userInfoApi.findById(visitors.getVisitorUserId());
                if (userInfo != null) {
                    BeanUtils.copyProperties(userInfo, vo);
                }

                // 查询你和访客的缘分值
                long score = recommendUserApi.queryScore(userId, visitors.getVisitorUserId());
                vo.setMatchRate((int) score);

                // 添加vo到集合
                voList.add(vo);
            }
        }

        return new PageResult(page, pagesize, (int) count, voList);
    }

    @Override
    // db.user_like.remove({userId:3, likeUserId:20})
    public void delete(Long userId, Long fanId) {
        Query query = new Query(Criteria.where("userId").is(fanId).and("likeUserId").is(userId));
        mongoTemplate.remove(query, UserLike.class);
    }

    @Override
    public void save(Long userId, Long likeUserId) {
        // 如果不是双向好友，就添加单向好友关系
        Query query1 = new Query(Criteria.where("friendId").is(likeUserId)
                .and("userId").is(userId));

        Query query2 = new Query(Criteria.where("userId").is(likeUserId)
                .and("likeUserId").is(userId));

        Query query3 = new Query(Criteria.where("userId").is(userId)
                .and("likeUserId").is(likeUserId));

        if(!mongoTemplate.exists(query1, Friend.class)){
            UserLike userLike = new UserLike();
            userLike.setUserId(userId);
            userLike.setLikeUserId(likeUserId);
            // 先清除，再添加
            mongoTemplate.remove(query3,UserLike.class);
            mongoTemplate.save(userLike);
        } // 如果对方是自己的粉丝，直接升级为好友
        else if(mongoTemplate.exists(query2,UserLike.class)){
            mongoTemplate.remove(query2,UserLike.class);
            mongoTemplate.remove(query3,UserLike.class);
            Friend friend = new Friend();
            friend.setId(new ObjectId());
            friend.setUserId(userId);
            friend.setFriendId(likeUserId);
            mongoTemplate.save(friend);


            friend.setId(new ObjectId());
            friend.setUserId(likeUserId);
            friend.setFriendId(userId);
            mongoTemplate.save(friend);
        }
    }
}
